<?php

namespace App\Model;

use DateTimeZone;
use Hyperf\HttpServer\Contract\RequestInterface;
use Phper666\JWTAuth\Util\JWTUtil;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * App\Distributor
 *
 * @property int $id
 * @property string $name 名称
 * @property int|null $category_id 类型
 * @property string $owner_name 负责人
 * @property string $phone 负责人手机号
 * @property string $password 密码
 * @property string|null $customer_service_phone 客服电话
 * @property string|null $number 编号
 * @property string|null $avatar 头像
 * @property string|null $openid 微信唯一标识
 * @property string|null $nickname 微信昵称
 * @property int|null $use_rate 使用率
 * @property string|null $area 区域
 * @property string|null $lat 位置
 * @property string|null $lng 位置
 * @property string|null $address 位置
 * @property string $rate 分成比例
 * @property int $total_profit 累计收益
 * @property int $orders_count 累计订单数
 * @property int $level 等级 最多4级
 * @property int $is_active 是否可用
 * @property string|null $introduction 简介
 * @property int|null $parent_id
 * @property string|null $api_token
 * @property int|null $province_id
 * @property int|null $city_id
 * @property int|null $area_id
 */
class YDistributors extends Model
{
    //
    public bool $timestamps = true;

    protected ?string $table = 'y_distributors';
    protected array $fillable = [
        'avatar','name', 'owner_name', 'phone', 'rate', 'area', 'address', 'lat',
        'lng', 'introduction', 'is_active',
        'settlement_type','balance','rate','service_image',
        'password','parent_id','level','customer_service_phone',
        'draw_active','draw_space','withdraw_account_bank_name',
        'withdraw_account_bank_card_no','withdraw_account_bank_card_username',
        'remark','third_account_id','device_count'
    ];

    const LEVEL_1 = 1;
    const LEVEL_2 = 2;
//    const LEVEL_3 = 3;
    const LEVEL_MAX = 2;
    const LEVEL_TYPE_AGENT = 'agent';
    const LEVEL_TYPE_MERCHANT = 'merchant';

    public static array $levelTypeMap = [
        self::LEVEL_TYPE_AGENT => '代理',
        self::LEVEL_TYPE_MERCHANT => '商家',
    ];


    public static array $levelMap = [
        self::LEVEL_1 => '一级分销',
        self::LEVEL_2 => '二级分销',
//        self::LEVEL_3 => '商家'
    ];

    const WITHDRAW_HANDLE_TYPE_MANUAL = 'manual';
    const WITHDRAW_HANDLE_TYPE_AUTO = 'auto';

    public static array $withdrawHandelTypeMap = [
        self::WITHDRAW_HANDLE_TYPE_MANUAL => '手动处理',
        self::WITHDRAW_HANDLE_TYPE_AUTO => '自动(仅微信)',
    ];

    const WITHDRAW_ACCOUNT_TYPE_WE_CHAT = 'we_chat'; //微信转账
    const WITHDRAW_ACCOUNT_TYPE_PUBLIC = 'public'; //对公账户
    const WITHDRAW_ACCOUNT_TYPE_PERSONAL = 'personal'; //个人账户

    public static array $withdrawAccountTypeMap = [
        self::WITHDRAW_ACCOUNT_TYPE_WE_CHAT => '微信转账',
        self::WITHDRAW_ACCOUNT_TYPE_PUBLIC => '对公账户',
        self::WITHDRAW_ACCOUNT_TYPE_PERSONAL => '个人账户',
    ];

    public static array $withdrawAccountInfoMap = [
        'no' => '账号',
        'name' => '名称',
        'phone' => '联系电话',
        'branch' => '开户行',
        'tax_number' => '税号',
        'openid' => '微信标识',
        'nickname' => '微信昵称',
    ];

    const SETTLEMENT_TYPE_NO = 'no';
    const SETTLEMENT_TYPE_NOW = 'now';
    const SETTLEMENT_TYPE_ONE_DAY = 'one_day';
    const SETTLEMENT_TYPE_SEVEN_DAY = 'seven_day';
    const SETTLEMENT_TYPE_MONTHLY = 'monthly';

    public static array $settlementTypeMap = [
        self::SETTLEMENT_TYPE_NO => '不结算',
        self::SETTLEMENT_TYPE_NOW => '即时结算',
        self::SETTLEMENT_TYPE_ONE_DAY => 'T + 1',
        self::SETTLEMENT_TYPE_SEVEN_DAY => 'T + 7',
        self::SETTLEMENT_TYPE_MONTHLY => '月结',
    ];

    /**解绑微信
     * @return void
     */
    public function unbindWeChat():void
    {
        $this->openid = null;
        $this->nickname = null;
        $this->save();
    }



    /**构造登陆态内容
     * @param $info
     * @return array
     */
    public function makeInfo($info): array
    {
        $user = [];
        $user['uid'] = $info->id;
        $user['id'] = $info->id;
        $user['name'] = $info->name;
        $user['phone'] = $info->phone;
        $user['avatar'] = $info->avatar;
        $user['owner_name'] = $info->owner_name;
        $user['level'] = $info->level;
        $user['rate'] = $info->rate;
        $user['customer_service_phone'] = $info->customer_service_phone;
        $user['service_image'] = $info->service_image;
        if($info->id == 10 || $info->parent_id == 10){
            $user['type'] = 'special';
        }else{
            $user['type'] = 'normal';
        }
        return $user;
    }

    /**获取登陆态
     * @param RequestInterface $request
     * @return array
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getInfo(RequestInterface $request,): array
    {
        $token = $request->getHeaderLine('Authorization');
        if ($token) {
//            $tokenArr = explode("Bearer ", $token);
//            $bool= redis()->exists($tokenArr[1]);
//            if(!$bool){
//                return [];
//            }
            $jwtArray = JWTUtil::getUserData($token);
            if (!isset($jwtArray['id'])) {
                return [];
            }
            $jwtArray['now'] = time();
            if ($jwtArray) {
                $jwtArray['exp'] = $jwtArray['exp']->setTimezone(new DateTimeZone('Asia/Shanghai'));
                $jwtArray['exp_time'] = $jwtArray['exp']->getTimestamp();
                if (time() > $jwtArray['exp_time']) {
                    return [];
                }
            }
            return $jwtArray;
        }
        return [];
    }


    public function station(){
        return $this->hasMany(YStation::class,'distributor_id','id');
    }

    public function device(){
        return $this->hasMany(YDevice::class,'distributor_id','id');
    }

    public function deviceProfit(){
        return $this->hasMany(YDistributorDevice::class,'distributor_id','id');
    }
}
